<template>
  <div class="class-editor-container">
    <el-card class="edit-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <el-button link type="primary" icon="el-icon-arrow-left" @click="goBack">返回</el-button>
          <span>编辑班级信息 - {{ formData.className }}</span>
        </div>
      </template>

      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="班级ID" prop="id">
          <el-input v-model="formData.id" disabled />
        </el-form-item>
        
        <el-form-item label="班级名称" prop="className" required>
          <el-input 
            v-model="formData.className" 
            placeholder="请输入2-20个字符的班级名称"
            clearable
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="学生人数" prop="classStuNum" required>
          <el-input-number 
            v-model="formData.classStuNum" 
            :min="0"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" native-type="submit" :loading="submitting">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { classApi } from '@/api/class'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)
const loading = ref(false)

// 表单数据
const formData = ref({
  id: '',
  className: '',
  classStuNum: 0
})

// 表单验证规则
const rules = {
  className: [
    { required: true, message: '班级名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  classStuNum: [
    { required: true, message: '请输入学生人数', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '人数应在0-100之间' }
  ]
}

// 加载班级详情
const loadClassInfo = async () => {
  loading.value = true
  try {
    const res = await classApi.getClassDetail(route.params.id)
    console.log('API响应:', res)
    
    const responseData = res.data || res
    if (!responseData?.id) {
      throw new Error('无效的班级数据格式')
    }

    formData.value = {
      id: responseData.id,
      className: responseData.className || responseData.class_name || '',
      classStuNum: responseData.classStuNum || responseData.class_stu_num || 0
    }
  } catch (error) {
    ElMessage.error(`获取班级信息失败: ${error.message}`)
    console.error('完整错误:', error)
    router.push('/class/list')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true
    await formRef.value.validate()
    
    const { id, className, classStuNum } = formData.value
    await classApi.updateClassInfo({ 
      id, 
      className: className.trim(),
      classStuNum 
    })
    
    ElMessage.success('班级信息更新成功')
    router.push('/class/list')
  } catch (error) {
    if (error !== 'cancel') {
      const errorMsg = error.response?.data?.message || error.message
      ElMessage.error(`保存失败: ${errorMsg}`)
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  loadClassInfo()
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  loadClassInfo()
})
</script>

<style scoped>
.class-editor-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.edit-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.card-header span {
  margin-left: 10px;
}

.el-form {
  margin-top: 20px;
}
</style>